extends Spatial


onready var MAIN = find_parent("MAIN")

var speed = 0.4
var normal = Vector3(0.0,1.0,0.0)
var rotspeed = 0.01*1024.0
var theta_limit = PI/2.0*0.9
var camtheta = 0
var body_phi = 0
var cam_speed = Vector2(0,0)
var camera
var can_look_around = true
var current_hand = ""

var beta_speed = 0.01
onready var camera_default_transform = $Camera.transform
onready var vp_size = get_viewport().size

class_name Player

# Called when the node enters the scene tree for the first time.

func _input(event):
	if event is InputEventMouseMotion:
		if not event.relative.length()>100.0:
			body_phi= wrapf(body_phi-event.relative.x * rotspeed/vp_size.x,-PI,PI)
			camtheta = clamp(camtheta - event.relative.y*rotspeed/vp_size.x,-theta_limit,theta_limit)


func _process(_delta):
	if Input.is_action_pressed("ui_down"):
		tune_beta(false, _delta)
	if Input.is_action_pressed("ui_up"):
		tune_beta(true, _delta)

	if can_look_around:
		camera.rotation.x +=  (camtheta-camera.rotation.x)*0.3
		var dphi = body_phi - rotation.y
		if dphi>PI:
			dphi = dphi - 2*PI
		elif dphi<-PI:
			dphi = dphi + 2*PI
		dphi*=0.3
		rotation.y=wrapf(rotation.y+dphi,-PI,PI)


func tune_beta(up, delta):
	var dir = Vector3(0,0,1)
	var step = (1 if up else -1)*delta
	MAIN.beta.z = wrapf(MAIN.beta.z+step, 0, 1)

func _ready():
	camera = $Camera
